package com.rongshu.view.discovery.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.eventbus.ArticleSetRead;
import com.rongshu.eventbus.DiscoverySearchResult;
import com.rongshu.eventbus.SearchResultAuthorState;
import com.rongshu.utils.Constant;
import com.rongshu.utils.ControlScrollLayoutManager;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.AdapterListener;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.adapter.AuthorListItemAdapter;
import com.rongshu.view.discovery.adapter.OtherArticleAdapter;
import com.rongshu.view.discovery.adapter.SearchResultPageAdapter;
import com.rongshu.view.discovery.bean.ArticleListItemBean;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.discovery.bean.SearchAllResponse;
import com.rongshu.view.discovery.contract.AuthorItemClickListener;
import com.rongshu.view.discovery.contract.SearchAuthorView;
import com.rongshu.view.discovery.presenter.SearchAllPresenter;
import com.rongshu.view.home.bean.LabelResponse;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * created by zhengweis on 2018/11/1.
 * description：综合搜索
 */
public class SearchResultAllFragment extends BaseFragment<SearchAllPresenter> implements SearchAuthorView {
    @BindView(R.id.article_list)
    RecyclerView articleList;
    @BindView(R.id.author_list)
    RecyclerView authorList;
    @BindView(R.id.aritlce_layout)
    LinearLayout articleLayout;
    @BindView(R.id.author_layout)
    LinearLayout authorLayout;
    @BindView(R.id.no_data_layout)
    RelativeLayout noDataLayout;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.more_article)
    TextView moreArticle;
    @BindView(R.id.more_author)
    TextView moreAuthor;
    private LabelResponse.ResponseBean bean;
    private List<ArticleListItemBean> articles;
    private List<AuthorDetailBean> authors;
    private OtherArticleAdapter searchArticleListAdapter;
    private AuthorListItemAdapter authorListItemAdapter;
    private String msg;
    private int clickPosition;
    private int pageIndex = 1;
    private int pageSize = 3;
    private int REQUEST_CODE = 1001;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_search_result_all;
    }


    /**
     * 接受输入框的信息
     *
     * @param data
     */
    @Subscribe
    public void onMessageEventPost(DiscoverySearchResult data) {
        pageIndex = 1;
        presenter.getData(data.getMsg(), pageIndex, pageSize);
    }

    /**
     * 同步用户 关注/未关注 状态
     *
     * @param data
     */
    @Subscribe
    public void onMessageEventPost(SearchResultAuthorState data) {
        for (AuthorDetailBean bean : authors) {
            if (bean.getUserid() == data.getAuthorId()) {
                bean.setIsConcern(data.getIsConcern());
            }
        }
        authorListItemAdapter.notifyDataSetChanged();
    }

    /**
     * 同步已读文章
     */
    @Subscribe
    public void onMessageEventPost(ArticleSetRead data) {
        for (ArticleListItemBean bean : articles) {
            if (bean.getContribute_id() == data.getContribute_id()) {
                bean.setRead(1);
            }
        }
        if (searchArticleListAdapter != null) searchArticleListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initViews() {
        ControlScrollLayoutManager linearLayoutManager1 = new ControlScrollLayoutManager(getActivity());
        linearLayoutManager1.setScrollEnabled(false);
        articleList.setLayoutManager(linearLayoutManager1);
        articles = new ArrayList<>();
        searchArticleListAdapter = new OtherArticleAdapter(getActivity(), articles);
        articleList.setAdapter(searchArticleListAdapter);
        searchArticleListAdapter.setAdapterListener(new AdapterListener() {
            @Override
            public void callBack(Object object) {
                ArticleListItemBean response = (ArticleListItemBean) object;
                presenter.toArticleDetailsAct(response);
            }
        });

        ControlScrollLayoutManager linearLayoutManager2 = new ControlScrollLayoutManager(getActivity());
        linearLayoutManager2.setScrollEnabled(false);
        authorList.setLayoutManager(linearLayoutManager2);
        authors = new ArrayList<>();
        authorListItemAdapter = new AuthorListItemAdapter(getActivity(), authors);
        authorListItemAdapter.setHasStableIds(true);
        authorList.setAdapter(authorListItemAdapter);
        authorListItemAdapter.setAdapterListener(new AuthorItemClickListener() {
            @Override
            public void onItemClickListener(int type, int position) {
                clickPosition = position;
                AuthorDetailBean bean = authors.get(clickPosition);
                if (type == AuthorItemClickListener.ADD_ATTENTION) {
                    if (bean.getIsConcern() == 1) {
                        presenter.cancelConcernWith(bean.getUserid());
                    } else {
                        presenter.ConcernWith(bean.getUserid());
                    }
                } else if (type == AuthorItemClickListener.INTENT_DETAILS) {
                    if (UserInfoUtils.getUserInfo() == null){
                        LoginUtils.toLogin(getActivity());
                    } else {
                        Intent intent = new Intent();
                        if (bean.getUserid() == UserInfoUtils.getUserId()) {
                            intent.setClass(getActivity(), PersonDetailsActivity.class);
                            startActivity(intent);
                        } else {
                            intent.setClass(getActivity(), UserHomePageActivity.class);
                            int userid = bean.getUserid();
                            intent.putExtra("UserId", userid);
                            startActivityForResult(intent, REQUEST_CODE);
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        bean = (LabelResponse.ResponseBean) bundle.getSerializable("searchMsg");
        setPresenter(new SearchAllPresenter(getActivity()), this);
        if (bean != null) {
            msg = bean.getTitle();
            presenter.getData(msg, pageIndex, pageSize);
        }

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void success(Object object, int tag) {
        articles.clear();
        SearchAllResponse response = (SearchAllResponse) object;
        if (response == null) {
            return;
        }
        articles.addAll(response.getResponse().getContributeList());
        searchArticleListAdapter.notifyDataSetChanged();
        articleLayout.setVisibility(articles.size() == 0 ? View.GONE : View.VISIBLE);
        moreArticle.setVisibility(articles.size() < 3 ? View.GONE : View.VISIBLE);

        authors.clear();
        authors.addAll(response.getResponse().getUserModelList());
        authorListItemAdapter.notifyDataSetChanged();
        authorLayout.setVisibility(authors.size() == 0 ? View.GONE : View.VISIBLE);
        moreAuthor.setVisibility(authors.size() < 3 ? View.GONE : View.VISIBLE);

        noDataLayout.setVisibility(authors.size() == 0 && articles.size() == 0
                ? View.VISIBLE : View.GONE);
        line.setVisibility(authors.size() == 0 || articles.size() == 0
                ? View.GONE : View.VISIBLE);
    }

    @Override
    public void faild(Object object, int tag) {

    }

    @Override
    public void concernSuccess() {
        authors.get(clickPosition).setIsConcern(authors.get(clickPosition).getIsConcern() == 0 ? 1 : 0);
        authorListItemAdapter.notifyDataSetChanged();
        sendConcernAuthor();
    }

    private void sendConcernAuthor() {
        SearchResultAuthorState state = new SearchResultAuthorState();
        state.setAuthorId(authors.get(clickPosition).getUserid());
        state.setIsConcern(authors.get(clickPosition).getIsConcern());
        EventBus.getDefault().post(state);
    }

    @OnClick({R.id.more_article, R.id.more_author})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.more_article:
                if (callback != null) {
                    callback.onCallBack(SearchResultPageAdapter.MORE_ARTICLE);
                }
                break;
            case R.id.more_author:
                if (callback != null) {
                    callback.onCallBack(SearchResultPageAdapter.MORE_AUTHOR);
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            boolean booleanExtra = data.getBooleanExtra(Constant.IS_COLLECT, false);
            authors.get(clickPosition).setIsConcern(booleanExtra ? 1 : 0);
            authorListItemAdapter.notifyDataSetChanged();
        }
    }
}
